package com.strongbj.iot.devices.newlight.request.handle;

import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.newlight.common.NetMapping;
import com.strongbj.iot.devices.newlight.entity.Reader;
import com.strongbj.iot.devices.newlight.entity.T;
import com.strongbj.iot.devices.newlight.entity.Tag;
import com.strongbj.iot.devices.newlight.entity.UnBindTagData;
import com.strongbj.iot.devices.newlight.entity.UnBindTagReturnData;
import com.strongbj.iot.devices.newlight.message.NewLightMQMessage;
import com.strongbj.iot.devices.newlight.message.NewLightOSMessageFactory;
import com.strongbj.iot.devices.newlight.service.ReaderService;
import com.strongbj.iot.devices.newlight.service.TagService;
import com.strongbj.iot.mq.producer.TopicSender;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;

/**
 * 标签解绑事件
 * 
 * @author lei_w
 *
 */
public class UnBindTagHandle implements IMessageHandle<NewLightMQMessage, Object> {

	private static Logger logger = LogManager.getLogger(UnBindTagHandle.class.getName());

	private TagService tagService = (TagService) ContextUtils.getBean("tagService");

	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");

	private NewLightOSMessageFactory newLightOSMessageFactory = (NewLightOSMessageFactory) ContextUtils
			.getBean("newLightOSMessageFactory");

	private final static byte UNBIND_TAG_COMMAND = Integer.valueOf("4D", 16).byteValue();
	
	private ReaderService readerService = (ReaderService) ContextUtils.getBean("readerService");
	
	@Override
	public boolean isHandle(NewLightMQMessage msg) {
		if (msg.getActioncode().equals("unbindTag")) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, NewLightMQMessage msg) {
		logger.info("====收到标签解绑====");
		UnBindTagData data = null;
		try {
			data = ((JSONObject) msg.getPostdata()).toJavaObject(UnBindTagData.class);
			QueryWrapper<Reader> query = new QueryWrapper<>();
			query.eq("code_", data.getReaderCode());
			Reader reader = readerService.getOne(query);
			
			this.unbindTag(reader,data); // 解绑标签
			//发送标签绑定命令（标签失联）
//			byte[] sendData = new byte[data.getLabs().size() * 4 + 2];
//			ByteUtil.intToByteArray(data.getLabs().size());
//			for(int i=0 ; i<data.getLabs().size(); i++) {
//				byte[] da = ByteUtil.ipToBytesByInet(data.getLabs().get(i));
//	    		System.arraycopy(da, 0, sendData, i * 4 + 2, 4);
//			}
//			byte[] req = newLightOSMessageFactory.createNewLightOSMessage(
//					ByteUtil.addressToBytes(data.getReaderCode()), UNBIND_TAG_COMMAND, sendData, T.getTimeStamp());
//			logger.info("标签解绑命令已下发 {}", ByteUtil.byteArrToHexString(req));
//			ByteBuf bs  = Unpooled.copiedBuffer(req);
//			NewLightReaderResponseHandleContext.channels.writeAndFlush(bs);
			// 更新数据库标签状态
			List<Tag> tags = new ArrayList<Tag>();
			for(String ip : data.getTags()) {
				Tag tag = new Tag();
				tag.setIp(ip);
				tag.setState(2);
				tags.add(tag);
			}
			tagService.updateBatchById(tags);

			//返回成功MQ消息
			NewLightMQMessage mes = new NewLightMQMessage();
			mes.setActioncode("unbindTagReturn");
			mes.setGUID(msg.getGUID());
			UnBindTagReturnData ubrd = new UnBindTagReturnData();
			ubrd.setSendUnbindCommandSuccess(true);
			ubrd.setReaderCode(data.getReaderCode());
			ubrd.setTags(data.getTags());
			mes.setPostdata(ubrd);
			logger.info("=========unBindTagReturn=======" + JSON.toJSONString(mes));
			topicSender.send("wh.reader.command.response", JSON.toJSONString(mes));
			return mes;
		}catch(Exception ex) {
			//返回失败MQ消息
			NewLightMQMessage mes = new NewLightMQMessage();
			mes.setActioncode("unbindTagReturn");
			mes.setGUID(msg.getGUID());
			UnBindTagReturnData ubrd = new UnBindTagReturnData();
			if(data!=null) {
				ubrd.setReaderCode(data.getReaderCode());
				ubrd.setTags(data.getTags());
			}
			ubrd.setErrorMessage(ex.getMessage());
			ubrd.setSendUnbindCommandSuccess(false);
			mes.setPostdata(ubrd);
			logger.info("=========unBindTagReturn=======" + JSON.toJSONString(mes));
			topicSender.send("wh.reader.command.response", JSON.toJSONString(mes));
			return mes;
		}
	}

	/**
	 * 向设备下发解绑标签命令
	 * @param datas
	 */
	private void unbindTag(Reader reader,UnBindTagData datas) {
		for(int i=0 ; i<datas.getTags().size(); i++) {
			final String tag = datas.getTags().get(i);
			byte[] bTag = ByteUtil.ipToBytesByInet(tag);
			byte[] timestamp = T.getTimeStamp();
			byte[] req = newLightOSMessageFactory.createNewLightOSMessage(
					ByteUtil.addressToBytes(datas.getReaderCode()), UNBIND_TAG_COMMAND, bTag, timestamp);
//			logger.info("标签解绑命令已下发 tag = {} 下发数据={}", datas.getTags().get(i),ByteUtil.byteArrToHexString(req));
			ByteBuf bs  = Unpooled.copiedBuffer(req);
			Channel channel = NetMapping.getInstance().getChannel(reader.getIp());
			ChannelFuture cf = channel.writeAndFlush(bs);
			cf.addListener(new ChannelFutureListener() {

				@Override
				public void operationComplete(ChannelFuture future) throws Exception {
					if (future.isSuccess()) {
						logger.info("发送标签解绑命令成功 设备编号:{} 标签编号:{} 命令={}  ", reader.getCode(),
								tag, ByteUtil.byteArrToHexString(req, true));
					} else {
						logger.debug("发送标签解绑命令失败 设备编号:{} 标签编号:{} 命令={}  ", reader.getCode(),
								tag, ByteUtil.byteArrToHexString(req, true));
					}
				}

			});
		}
	}

	@Override
	public void destory() {
		// TODO Auto-generated method stub
		
	}
}
